﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.Web.Http;
using System.Web.Security;
using System.Security;
using System.Security.Principal;
using MinistryStandardPlatformWeb.Models;
using MinistryStandardPlatformEntity;

namespace MinistryStandardPlatformWeb
{
    public static class CommonFunctions
    {
        private static MSPDataContext context;

        static CommonFunctions()
        {
            context = new MSPDataContext();
        }

        /// <summary>
        /// 获取一个4位随机数
        /// </summary>
        /// <returns></returns>
        public static string Get4BitsRandom()
        {
            Random rad = new Random();
            return rad.Next(1000, 10000).ToString();
        }

        /// <summary>
        /// 获取由当前时间（精确到秒)和4位随机数组成的字符串
        /// </summary>
        /// <returns></returns>
        public static string GetDateTimeStrAnd4BitsRandom()
        {
            Random rad = new Random();
            return DateTime.Now.ToString("yyyyMMddhh24mmss") + rad.Next(1000, 10000).ToString();
        }

        public static string ListToJsonStr<T>(List<T> list)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(list.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, list);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                return null;
            }
        }

        public static string ObjectToJsonStr<T>(T obj)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, obj);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                return null;
            }
        }

        public static T JsonStrToObject<T>(string jsonStr)
        {
            T obj = Activator.CreateInstance<T>();  //注意 要有T类型要有无参构造函数
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }


        public static UserＭodel GetLoginUser()
        {

            var id = HttpContext.Current.User.Identity as FormsIdentity;
            if (id != null && id.IsAuthenticated && id is FormsIdentity)
            {
                try
                {
                    return CommonFunctions.JsonStrToObject<UserＭodel>(id.Ticket.UserData);
                }
                catch
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        /*获取方向*/
        public static string TranslateDirection(string direction)
        {
            //正北 正西 正南 正东 西北 西南  东南 东北
            double dir = 0;
            if (!double.TryParse(direction, out dir))
                return "正北";
            if (dir > 22.5 && dir < 90 - 22.5)
            {
                return "东北";
            }
            else if (dir >= 90 - 22.5 && dir <= 90 + 22.5)
            {
                return "正东";
            }
            else if (dir > 90 + 22.5 && dir < 180 - 22.5)
            {
                return "东南";
            }
            else if (dir >= 180 - 22.5 && dir <= 180 + 22.5)
            {
                return "正南";
            }
            else if (dir > 180 + 22.5 && dir < 270 - 22.5)
            {
                return "西南";
            }
            else if (dir >= 270 - 22.5 && dir <= 270 + 22.5)
            {
                return "正西";
            }
            else if (dir > 270 + 22.5 && dir < 360 - 22.5)
            {
                return "西北";
            }
            else if (dir >= 360 - 22.5 && dir <= 360 || dir >= 0 && dir <= 22.5)
            {
                return "正北";
            }
            else
            {
                return "正北";
            }
        }

        /*解析报警信息*/
        public static bool ParseWarnInfo(RealTimeModel model, string warn)
        {
            if (!string.IsNullOrEmpty(warn) && warn.Length >= 43)//报警信息有用位数为前43位
            {
                for (int i = 0; i < 43; i++)
                {
                    model.GetType().GetProperty("warn" + i).SetValue(model, warn[i].ToString());
                }
                return true;
            }
            return false;
        }

        /*解析状态信息*/
        public static bool ParseStateInfo(RealTimeModel model, string state)
        {
            if (!string.IsNullOrEmpty(state) && state.Length >= 46)//报警信息有用位数为前46位
            {
                for (int i = 0; i < 46; i++)
                {
                    model.GetType().GetProperty("state" + i).SetValue(model, state[i].ToString());
                }
                return true;
            }
            return false;
        }
        /*获取车辆在线图标*/
        public static string GetVehicleIcon(string time, string acc)
        {
            string url = "";
            try
            {
                DateTime dt = Convert.ToDateTime(time);
                TimeSpan ts = DateTime.Now - dt;
                if(ts.TotalMilliseconds >= (30 * 60 * 1000))
                {//离线半个小时
                    url = "/Content/themes/zTreeStyle/img/diy/car.png";
                }
                 else 
                {
                    if (acc == "1") 
                    {
                        url = "/Content/themes/zTreeStyle/img/diy/6.png";
                    }
                    else
                    {
                        url = "/Content/themes/zTreeStyle/img/diy/4.png";
                    }
                }
            }
            catch
            {
                return "/Content/themes/zTreeStyle/img/diy/car.png";
            }
            return url;
        }

        public static string ToVarcharSqlParam(this string str)
        {
            return "'"+str+"'";
        }


        public static string GetSQL<T>(IQueryable<T> query,List<string> parameters)
        {
            string sql = query.ToString();
            sql = sql.Replace("[dbo].", "");
            for (int i = parameters.Count-1; i >=0; i--)
            {
                sql=sql.Replace("@p" + i, parameters[i]);
            }

            return sql;
        }

        /// <summary>
        /// 获取一个单位的所有子孙单位(不包括它自身)
        /// </summary>
        /// <param name="unitId">单位id</param>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public static List<string> GetAllChildrenUnits(string unitId,string userId)
        {
            var query = from r in context.RightsDetails
                        where
                        r.UserId == userId &&
                        r.NodeTYPE == true &&
                        r.HasRight == true &&
                        r.ParentNodeId == unitId
                        select r.NodeId;

            return query.ToList<string>().Concat<string>(query.ToList().SelectMany(t => GetAllChildrenUnits(t,userId))).ToList();
        } 
    }
}